package main

import (
	"context"
	"fmt"
	"time"
)

func withDeadLine(ctx context.Context) {

	for {
		select {
		case <-ctx.Done():
			fmt.Println("ready to exit")
			return
		default:
			fmt.Println("working...")
			time.Sleep(time.Second * 1)
		}
	}
}

func main() {
	// 手动 cancel()
	// ctx, cancel := context.WithCancel(context.Background())
	// 超时自动 timeout
	//ctx, cancel := context.WithTimeout(
	//	context.Background(), time.Second*3)
	// 定时自动 deadline
	ctx, cancel := context.WithDeadline(
		context.Background(),
		time.Now().Add(time.Second*3))
	go withDeadLine(ctx)
	time.Sleep(time.Second * 5)
	cancel()
}
